package microgame.toolset.datatable;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;

public class DataTable {
    private Hashtable<Integer, Row> rowSet = new Hashtable<>();

    private String firstRow;
    private String secondRow;

    public Row GetRow(int key) {
        return rowSet.get(key);
    }

    public void LoadDataFile(String path) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader(path));

        try {
            StringBuilder sb = new StringBuilder();
            // first line is all properties' key
            firstRow = br.readLine();
            secondRow = br.readLine();

            String line = br.readLine();
            while (line != null && line != "\r\n" && line != "\n") {
                ProcessLine(line);
                line = br.readLine();
            }
        } finally {
            br.close();
        }
    }

    private void ProcessLine(String line) {
        String[] keys = firstRow.split("\t");
        String[] types = secondRow.split("\t");
        String[] values = line.split("\t");

        if ((keys.length != types.length) || (keys.length != values.length) || (types.length != values.length)) {
            System.out.println("Error, invalid table!");
            return;
        }

        Row row = new Row();
        rowSet.put(Integer.parseInt(values[0]), row);

        for (int i = 0; i < types.length; ++i) {
            switch (types[i]) {
                case "string":
                    row.SetString(keys[i], values[i]);
                    break;
                case "float":
                    row.SetFloat(keys[i], Float.parseFloat(values[i]));
                    break;
                case "int":
                    row.SetInteger(keys[i], Integer.parseInt(values[i]));
                    break;
            }
        }
    }

    public ArrayList<Row> GetAllRows() {
        ArrayList<Row> rows = new ArrayList<Row>();

        for (Map.Entry<Integer, Row> entry : rowSet.entrySet()) {
            rows.add(entry.getValue());
        }

        return rows;
    }

    public ArrayList<Integer> GetAllKeys() {
        ArrayList<Integer> keys = new ArrayList<Integer>();

        for (Map.Entry<Integer, Row> entry : rowSet.entrySet()) {
            keys.add(entry.getKey());
        }

        return keys;
    }
}
